package com.aerospace.example.hello;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName HelloWorldServer
 * @Description
 * @Author yuhang11
 * @Date 2021/7/8 1:42 下午
 * @Version 1.0
 */
@Slf4j
public class HelloWorldServer {
    private Server server;

    public static void main(String[] args) throws Exception {
        final HelloWorldServer server = new HelloWorldServer();
        server.start();
        server.blockUntilShutdown();
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null){
            server.awaitTermination();
        }
    }

    private void start() throws IOException {
        int port = 50051;
        server = ServerBuilder.forPort(port)
                .addService(new GreeterImpl())
                .build()
                .start();
        log.info("Server started, listening on "+ port);
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                log.info("**** 关闭JVM时，关闭gRPC Server*****");
                try {
                    HelloWorldServer.this.stop();
                }catch (Exception e){
                    e.printStackTrace();
                }
                log.info("**** gRPC Server 已关闭 *****");
            }
        });
    }

    private void stop() throws InterruptedException {
        if (server!=null){
            server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
        }
    }


    static class GreeterImpl extends GreeterGrpc.GreeterImplBase{
        @Override
        public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver){
            HelloReply reply = HelloReply.newBuilder().setMessage("Hello" + req.getName()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }
}
